package com.xfb.jdbc.sqlSession;

import com.xfb.jdbc.pojo.Configuration;
import com.xfb.jdbc.pojo.MappedStatement;

import java.lang.reflect.*;
import java.util.List;

/**
 * @Auther: Xing Fang Bin
 * @Date: 2021/07/01/11:44
 * @Description:
 */
public class DefaultSession implements Session {

    private Configuration configuration;

    public DefaultSession(Configuration configuration) {
        this.configuration = configuration;
    }

    @Override
    public <E> List<E> selectList(String statementId, Object... params) throws Exception {
        MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statementId);
        List<Object> query = new SimpleExecutor().query(configuration, mappedStatement, params);
        return (List<E>) query;
    }

    @Override
    public <T> T selectOne(String statementId, Object... params) throws Exception {
        List<Object> objects = selectList(statementId, params);
        if (objects != null && objects.size() == 1) {
            return (T) objects.get(0);
        } else {
            throw new RuntimeException("未查询到结果或查询结果过多");
        }
    }

    @Override
    public Integer update(String statementId, Object... params) throws Exception {
        MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statementId);
        int update = new SimpleExecutor().update(configuration, mappedStatement, params);
        return update;
    }

    @Override
    public <T> T getMapper(Class<?> mapperClass) {
        // 使用JDK动态代理为DAO接口生成代理对象并返回 使用代理对象调用接口中的任意方法时，都会执行invoke方法
        Object proxyInstance = Proxy.newProxyInstance(DefaultSession.class.getClassLoader(), new Class[]{mapperClass}, new InvocationHandler() {
            @Override       //proxy：当前代理对象的应用   method：被调用方法的引用，如selectList、selectOne     args：代理的参数、如User实体
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                // 其实还是执行JDBC代码，根据不同情况，来判断执行哪个方法selectList还是selectOne

                // 准备参数:selectList或者selectOne的参数
                // 1：statementId
                String methodName = method.getName();
                String className = method.getDeclaringClass().getName();
                String statementId = className + "." + methodName;
                // 2：params：args
                // 获取被调用方法的返回值类型，来判断选择哪一个方法 selectList还是selectOne
                Type genericReturnType = method.getGenericReturnType();
                /*String typeName = genericReturnType.getTypeName();
                if (typeName.equals("java.lang.Integer") ||
                        typeName.equals("java.lang.Byte") ||
                        typeName.equals("java.lang.Double") ||
                        typeName.equals("java.lang.Long") ||
                        typeName.equals("java.lang.Short") ||
                        typeName.equals("java.lang.Character") ||
                        typeName.equals("java.lang.Boolean") ||
                        typeName.equals("java.lang.Float")) {
                    Integer update = update(statementId, args);
                    return update;
                }*/
                MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statementId);
                String sql = mappedStatement.getSql();
                if (sql.startsWith("update") || sql.startsWith("delete") || sql.startsWith("insert")) {
                    Integer update = update(statementId, args);
                    return update;
                }
                // ParameterizedType：是否是泛型，是泛型代表返回类型为List<E>
                if (genericReturnType instanceof ParameterizedType) {
                    List<Object> selectList = selectList(statementId, args);
                    return selectList;
                } else {
                    Object selectOne = selectOne(statementId, args);
                    return selectOne;
                }

            }
        });
        return (T) proxyInstance;
    }
}
